package push

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"

	"github.com/astaxie/beego"

	"chainserver/env"
)

var httpActivityClient *http.Client

func init() {
	httpActivityClient = &http.Client{}
}

func PushToActivityPlayer(from *Player, to *Player, action int, values []int64, goodsId, serverIP string) {
	var fromUID int64
	var province, city int64
	var fromName, fromHeadImg string
	if from != nil {
		fromUID = from.UID
		fromName = from.Name
		fromHeadImg = from.HeadImg
		province = from.Province
		city = from.City
	}
	if serverIP == "" {
		return
	}
	u := fmt.Sprintf("http://%s/push", serverIP)
	msg := env.BroadcastMessage{
		FromUID:     fromUID,
		FromName:    fromName,
		FromHeadImg: fromHeadImg,
		Province:    province,
		City:        city,
		ToUID:       to.UID,
		Action:      action,
		Values:      values,
		GoodsId:     goodsId,
	}
	body, _ := json.Marshal(&msg)
	res, err := httpActivityClient.Post(u, "application/json", bytes.NewReader(body))
	if err != nil {
		beego.Error("发送推送到activity广播服务器, err:", err.Error())
		return
	}
	defer res.Body.Close()
	buf := new(bytes.Buffer)
	buf.ReadFrom(res.Body)
	beego.Info(fmt.Sprintf("发送推送到activity广播服务器, url: %s, uid: %d, action: %d, msg: %s, code: %d, result: %s", u, to.UID, action, body, res.StatusCode, buf.String()))
}
